using System;
using System.Collections.Generic;
using System.Linq;
using Phoenix.Framework;

namespace Phoenix.Filters
{
    public class FilterAttributeFilterProvider : IFilterProvider
    {
        private readonly bool cacheAttributeInstances;

        public FilterAttributeFilterProvider()
            : this(true)
        {
        }

        public FilterAttributeFilterProvider(bool cacheAttributeInstances)
        {
            this.cacheAttributeInstances = cacheAttributeInstances;
        }

        protected virtual IEnumerable<FilterAttribute> GetActionAttributes(IActionDescriptor actionDescriptor)
        {
            return actionDescriptor.GetFilterAttributes(cacheAttributeInstances);
        }

        protected virtual IEnumerable<FilterAttribute> GetControllerAttributes(IActionDescriptor actionDescriptor)
        {
            return actionDescriptor.ControllerDescriptor.GetFilterAttributes(cacheAttributeInstances);
        }

        public virtual IEnumerable<Filter> GetFilters(ControllerContext controllerContext, IActionDescriptor actionDescriptor)
        {
            if (controllerContext == null)
                return Enumerable.Empty<Filter>();

            var controller = controllerContext.Controller;
            if (controller == null)
                return Enumerable.Empty<Filter>();

            var typeFilters = GetControllerAttributes(actionDescriptor)
                .Select(attr => new Filter(attr, FilterScope.Controller));
            var methodFilters = GetActionAttributes(actionDescriptor)
                .Select(attr => new Filter(attr, FilterScope.Action));

            return typeFilters.Concat(methodFilters).ToList();
        }
    }
}